<script lang="tsx" setup>
import { nextTick, onMounted, ref } from 'vue';
import { NButton, NPopconfirm, NText, useMessage } from 'naive-ui';
import { delDictType, getPageList } from '@/service/api/developer/dictType';
import { delDictData, getPageList as dictDataPageList } from '@/service/api/developer/dictData';
import type { DictDataVo, DictTypeVo } from '@/service/types/developer';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { $t } from '@/locales';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { useBoolean } from '~/packages/hooks/src';
import DictTypeForm from './components/dict-type-form.vue';
import DictDataForm from './components/dict-data-form.vue';
const message = useMessage();
const handleLoad = () => {};
const appStore = useAppStore();
const { bool: dictTypeVisible, setTrue: openDictTypeVisible } = useBoolean();
const dictTypeOperateType = ref<NaiveUI.TableOperateType>('add');
const dictTypeListloading = ref<boolean>(true);
const dictList = ref<Array<DictTypeVo>>([]);
const xRef = ref(0);
const yRef = ref(0);
const showDropdownRef = ref(false);
const searchValue = ref('');
const currentDictTypeId = ref();
const getDictTypeList = (value: any) => {
  dictTypeListloading.value = true;
  getPageList({ dictName: value } as DictTypeVo).then(res => {
    dictTypeListloading.value = false;
    // @ts-expect-error 忽略封装Reuest错误
    dictList.value = res.data.rows as Array<DictTypeVo>;
  });
};
const handleSearch = () => {
  getDictTypeList(searchValue.value);
};
const handleSearchClear = () => {
  getDictTypeList('');
};
const init = () => {
  getDictTypeList('');
};
onMounted(() => init());
const currentDict = ref<DictTypeVo>();
function renderCustomHeader() {
  return (
    <div class="flex flex-col" style={{ padding: ' 9px 12px' }}>
      {/* <NText depth={2}>{currentDict.value?.dictName}</NText> */}
      <NText depth={2}>{currentDict.value?.dictType}</NText>
    </div>
  );
}

const handleContextMenu = (e: MouseEvent, dict: DictTypeVo) => {
  e.preventDefault();
  currentDict.value = dict;
  showDropdownRef.value = false;
  nextTick().then(() => {
    showDropdownRef.value = true;
    xRef.value = e.clientX;
    yRef.value = e.clientY;
  });
};

const handleSelect = (key: string | number) => {
  showDropdownRef.value = false;
  handleChangeDict(key as string);
};
const onClickoutside = () => {
  showDropdownRef.value = false;
};

// 待
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: dictDataPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 20,
    dictType: ''
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'dictLabel',
      title: '字典名称',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'dictValue',
      title: '字典值',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'dictSort',
      title: '字典排序',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'remark',
      title: '备注',
      align: 'center',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (row: DictDataVo) => {
        return (
          <>
            <div class="flex-center gap-10px">
              <NButton
                tag="a"
                type="primary"
                size="small"
                text
                onClick={() => {
                  handleEditorDictData(row.dictCode as number);
                }}
              >
                {{
                  icon: () => <SvgIcon icon="ant-design:edit-outlined" />
                }}
              </NButton>
              <NPopconfirm
                onPositiveClick={() => {
                  handleDelete(row?.dictCode as number);
                }}
                onNegativeClick={() => {
                  (window as any).$message.info('已取消删除');
                }}
              >
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton text tag="a" type="error" ghost size="small">
                      {{
                        icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                      }}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </div>
          </>
        );
      }
    }
  ]
});
const {
  drawerVisible,
  operateType,
  currentId,
  handleAdd,
  customerEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);
const currentDictType = ref<any>('');
const dictDataTitle = ref('字典类型');
const handleClickDictType = (dict: DictTypeVo | undefined) => {
  const isFlag = currentDictType.value === dict?.dictId;
  currentDictType.value = isFlag ? undefined : dict?.dictId;
  if (isFlag) {
    searchParams.dictType = undefined;
    dictDataTitle.value = `字典类型`;
  } else {
    dictDataTitle.value = `字典类型 - ${dict?.dictName}`;
    searchParams.dictType = dict?.dictType;
  }
  getData();
  currentDict.value = dict;
};
const addOptions = ref([
  {
    label: '新增字典类型',
    key: 'type'
  },
  {
    label: '新增字典数据',
    key: 'data'
  }
]);
const options = ref([
  {
    render: renderCustomHeader,
    key: 'header',
    type: 'render'
  },
  {
    label: '修改字典类型',
    key: 'editor'
  },
  {
    label: '删除字典类型',
    key: 'remove'
  }
]);
const handleAddDictType = () => {
  dictTypeOperateType.value = 'add';
  openDictTypeVisible();
};
const handleEditDictType = () => {
  dictTypeOperateType.value = 'edit';
  currentDictTypeId.value = currentDict.value?.dictId;
  openDictTypeVisible();
};
const handleChangeDict = (key: string) => {
  if (key === 'editor') {
    handleEditDictType();
  } else if (key === 'remove') {
    handleRemoveDictType();
  }
};
const handleRemoveDictType = async () => {
  const loadinginstance = message.loading('正在处理中');
  const { error } = await delDictType(currentDict.value?.dictId);
  loadinginstance.destroy();
  if (!error) {
    message.success('删除成功');
    getDictTypeList(searchValue.value);
  }
};
const handleAddDictData = async () => {
  if (currentDict?.value) {
    handleAdd();
  } else {
    (window as any).$message.error('请选择字典类型');
  }
};
const handleAddSelect = (key: string) => {
  switch (key) {
    case 'type':
      handleAddDictType();
      break;
    case 'data':
      handleAddDictData();
      break;
    default:
      console.error('未知类型');
      break;
  }
};
const handleEditorDictData = (dictData: number) => {
  if (currentDict?.value) {
    customerEdit(dictData);
  } else {
    (window as any).$message.error('请选择字典类型');
  }
};
const requestRemove = async (id: number | number[]): Promise<boolean> => {
  const loadinginstance = (window as any).$message.loading('正在处理中');
  const { data, error } = await delDictData(id);
  loadinginstance.destroy();
  if (!error) {
    (window as any).$message.success(data?.msg);
    return Promise.resolve(true);
  }
  throw new Error('false');
};
const handleDelete = async (id: number) => {
  const result = await requestRemove(id as number);
  if (result) {
    onDeleted();
  }
};
const handleBatchDelete = async () => {
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定删除这些吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await requestRemove(checkedRowKeys.value as unknown as number[]);
      if (result) {
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
</script>

<template>
  <div>
    <NGrid y-gap="12" x-gap="12" responsive="screen" item-responsive>
      <NGi span="24 s:24 m:5">
        <NCard :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper sm:h-full">
          <template #header>
            <NInputGroup>
              <NInput
                v-model:value="searchValue"
                passively-activated
                clearable
                class="w-80%"
                :on-clear="handleSearchClear"
              />
              <NButton type="primary" ghost @click="handleSearch">搜索</NButton>
            </NInputGroup>
          </template>
          <NSpin :show="dictTypeListloading">
            <NList v-if="dictList.length > 0" :show-divider="false" hoverable clickable class="list">
              <NInfiniteScroll :distance="10" @load="handleLoad">
                <NListItem
                  v-for="(dict, index) in dictList"
                  :key="index"
                  :class="dict.dictId === currentDictType ? 'button-tab' : ''"
                  @contextmenu="handleContextMenu($event, dict)"
                  @click="handleClickDictType(dict)"
                >
                  <template #default>
                    <div class="flex flex-justify-between">
                      <div>{{ dict.dictName }}</div>
                      <NText depth="3">
                        {{ dict.dictType }}
                      </NText>
                    </div>
                  </template>
                </NListItem>
              </NInfiniteScroll>
            </NList>
            <div v-else class="w-100% flex flex-col flex-justify-center flex-items-center">
              <SvgIcon class="font-size-140px" local-icon="empty" />
              <NText depth="3">暂无数据</NText>
            </div>
          </NSpin>
          <NDropdown
            placement="bottom-start"
            trigger="manual"
            :x="xRef"
            :y="yRef"
            :options="options"
            :show="showDropdownRef"
            :on-clickoutside="onClickoutside"
            @select="handleSelect"
          />
        </NCard>
      </NGi>
      <NGi span="24 s:24 m:19">
        <div class="h-100% min-h-430px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
          <NCard :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
            <template #header>
              <div v-if="dictDataTitle">
                {{ dictDataTitle }}
              </div>
              <div v-else></div>
            </template>
            <template #header-extra>
              <TableHeaderOperation
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                @add="handleAdd"
                @refresh="getData"
              >
                <template #default>
                  <NDropdown trigger="hover" :options="addOptions" @select="handleAddSelect">
                    <NButton size="small" ghost type="primary">
                      <template #icon>
                        <icon-ic-round-plus class="text-icon" />
                      </template>
                      {{ $t('common.add') }}
                    </NButton>
                  </NDropdown>

                  <NButton
                    size="small"
                    ghost
                    type="error"
                    :disabled="checkedRowKeys.length === 0"
                    @click="handleBatchDelete"
                  >
                    <template #icon>
                      <icon-ic-round-delete class="text-icon" />
                    </template>
                    {{ $t('common.batchDelete') }}
                  </NButton>
                  <NButton size="small" ghost type="primary" @click="handleClickDictType(undefined)">全部显示</NButton>
                </template>
              </TableHeaderOperation>
            </template>
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns"
              :data="data"
              size="small"
              :flex-height="!appStore.isMobile"
              :scroll-x="962"
              :loading="loading"
              remote
              :row-key="row => row.dictCode"
              :pagination="mobilePagination"
              class="sm:h-full"
            >
              <template #empty>
                <Empty />
              </template>
            </NDataTable>
          </NCard>
        </div>
      </NGi>
    </NGrid>
    <DictTypeForm
      v-model:visible="dictTypeVisible"
      :operate-type="dictTypeOperateType"
      :current-dict-type-id="currentDictTypeId"
      @submitted="getDictTypeList('')"
    />
    <DictDataForm
      v-model:visible="drawerVisible"
      :operate-type="operateType"
      :current-id="currentId"
      :current-dict="currentDict"
      @submitted="getData()"
    />
  </div>
</template>

<style lang="scss" scoped>
.list {
  height: calc(100vh - 210px);
  overflow: auto;
}
.button-tab {
  // color: var(--soy-primary-color);
  border-color: var(--n-color-hover);
}
</style>
